package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.query.EmployeeQueryObject;
import cn.wolfcode.query.PageResult;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Security;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleService roleService;

    @RequiresPermissions(value = {"employee:list","员工列表"},logical = Logical.OR)
    //@RequiredPermission(name = "员工列表", expression = "employee:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
//       System.out.println(SecurityUtils.getSubject().hasRole("ADMIN"));
//       System.out.println(SecurityUtils.getSubject().isPermitted("employee:list"));


        //分页查询
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        //查询部门信息
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);
        return "employee/list";
    }

    @RequiresPermissions(value = {"employee:input","员工编辑"},logical = Logical.OR)
    //@RequiredPermission(name = "员工编辑", expression = "employee:input")
    @RequestMapping("/input")
    public String input(Model model, Long id) {
        //查询所有的部门名称
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);
        //查询所有的角色
        List<Role> roles = roleService.listAll();
        model.addAttribute("roles", roles);
        //判断id是否为空
        if (id != null) {
            //不为空则表示是编辑操作
            Employee employee = employeeService.get(id);

            model.addAttribute("employee", employee);
        }
        return "employee/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids) {
        //判断id是否为空
        if (employee.getId() != null) {
            //不为空则表示是更改操作
            employeeService.update(employee, ids);
        } else {
            //为空表示新增操作
            employeeService.save(employee, ids);
        }
        // int i = 1/0;
        return new JsonResult();
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        //判断id是否为空
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list.do";
    }


    /**
     * 修改密码跳转视图
     *
     * @return
     */
    @RequestMapping("/updatePwdView")
    public String updatePwdView() {
        return "/employee/updatePwd";
    }


    /**
     * 检查原密码是否和查询出来的密码一致
     *
     * @param oldPassword
     * @return
     */
    @RequestMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String oldPassword, String newPassword) {
        //查询当前当前用户
        Subject subject = SecurityUtils.getSubject();
        Employee employee = (Employee) subject.getPrincipal();
        //查询当前用户的密码
        String pwd = employee.getPassword();
        //将输入的原密码进行加密
        Md5Hash oldPwd = new Md5Hash(oldPassword, employee.getName());
        //判断当前密码是否和输入的原密码是否相同
        if (!pwd.equals(oldPwd.toString())) {
            return new JsonResult(false, "输入的密码与原密码不一致,请重新输入");
        }
        //将输入的新密码进行加密
        Md5Hash newPwd = new Md5Hash(newPassword, employee.getName());
        employeeService.updatePwdByEmpId(newPwd.toString(), employee.getId());
        subject.logout();
        return new JsonResult();
    }


    @RequestMapping("/resetPwd")
    @ResponseBody
    public JsonResult resetPwd(String newPassword, Long id) {

        //首先要判断当前用户是否为管理员
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        if (employee.isAdmin()) {
            //根据id获取被该密码的名字
            String name = employeeService.get(id).getName();
            //将新密码进行加密
            Md5Hash newPwd = new Md5Hash(newPassword,name);
            employeeService.updatePwdByEmpId(newPwd.toString(), id);
            return new JsonResult();
        } else {
            return new JsonResult(false, "不是管理员无权操作");
        }

    }

    @RequestMapping("/checkEmployee")
    public String checkEmployee(Model model, Long id) {
        //根据id获取employee对象
        if (id != null) {
            Employee employee = employeeService.get(id);
            model.addAttribute("employee", employee);
        }
        return "/employee/resetPwd";
    }


    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(Long[] ids) {
        employeeService.batchDelete(ids);
        return new JsonResult();

    }

    /**
     * 插件要求返回valid:false(验证不通过) valid:true(验证通过)
     * 远程验证
     *
     * @param name
     * @return
     */
    @RequestMapping("/checkName")
    @ResponseBody
    public HashMap checkName(String name, Long id) {
        HashMap<Object, Object> map = new HashMap<>();
        //1.判断id是否为null
        if (id != null) {
            //id不为null说明是编辑操作,通过id获取对象的name
            String eName = employeeService.get(id).getName();
            //判断是否和页面传过来的name相同
            if (name.equals(eName)) {
                //相同,验证通过
                map.put("valid", true);
                return map;
            } else {
                //不同,判断传过来的name是否被注册
                Employee employee = employeeService.selectByName(name);
                map.put("valid", employee == null);
                return map;
            }
        } else {
            //id为空表示新增操作,只需判断name是否别注册即可
            Employee employee = employeeService.selectByName(name);
            map.put("valid", employee == null);
            return map;
        }
    }


    /**
     * 设置禁用状态
     * @param id
     * @return
     */
    @RequestMapping("/disStatus")
    @ResponseBody
    public JsonResult disStatus(Long id){
        //根据员工id设置其状态为禁用
        employeeService.updateStatusByEmpId(false,id);
        return new JsonResult();
    }
    /**
     * 设置恢复状态
     * @param id
     * @return
     */
    @RequestMapping("/reStatus")
    @ResponseBody
    public JsonResult reStatus(Long id){
        //根据员工id设置其状态为正常
        employeeService.updateStatusByEmpId(true,id);
        return new JsonResult();
    }


    /**
     * 导出功能
     * @param response
     * @throws IOException
     */
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //设置文件下载的响应头
        response.setHeader("content-Disposition","attachment;filename=employee.xls");
        //创建Excel文件
        Workbook wb = employeeService.exportXls();
        //把Excel的数据输出给浏览器
        wb.write(response.getOutputStream());

    }


    /**
     * 导入功能
     * @param file
     * @return
     */
    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {
        employeeService.importXls(file);
        return new JsonResult();
    }


}

